package com.neusoft.bizcore.schedule.converter;

import java.util.List;

import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.Trigger.TriggerState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.schedule.dto.JobDetailDTO;
import com.neusoft.bizcore.web.dto.AbstractConverter;

import lombok.extern.slf4j.Slf4j;

/**
 * description
 *
 * @author sunchf
 * @date 2018年12月26日 下午2:44:09
 */
@Slf4j
@Component
public class JobConverter extends AbstractConverter<JobKey, JobDetailDTO> {

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    @Override
    public JobKey toModel(JobDetailDTO dto) {
        return null;
    }

    @Override
    public JobDetailDTO toDTO(JobKey jobKey, boolean forListView) {
        JobDetail jobDetail = null;
        try {
            jobDetail = this.schedulerFactoryBean.getScheduler().getJobDetail(jobKey);
        } catch (final SchedulerException e) {
            JobConverter.log.error(e.getMessage(), e);
            return null;
        }
        if (null == jobDetail) {
            return null;
        }
        final JobDetailDTO jobDetailDTO = new JobDetailDTO();
        jobDetailDTO.setJobKey(jobDetail.getKey().toString());
        jobDetailDTO.setJobGroup(jobDetail.getKey().getGroup());
        jobDetailDTO.setJobName(jobDetail.getKey().getName());
        jobDetailDTO.setDescription(jobDetail.getDescription());
        jobDetailDTO.setDurable(jobDetail.isDurable());

        try {
            final List<? extends Trigger> list = this.schedulerFactoryBean.getScheduler()
                    .getTriggersOfJob(jobDetail.getKey());
            boolean paused = true;
            for (final Trigger trigger : list) {
                final TriggerState state = this.schedulerFactoryBean.getScheduler().getTriggerState(trigger.getKey());
                if (TriggerState.NORMAL.equals(state)) {
                    paused = false;
                }
            }
            jobDetailDTO.setPaused(paused);
            jobDetailDTO.setTriggerCount(list.size());
        } catch (final SchedulerException e) {
            JobConverter.log.error("", e);
        }
        return jobDetailDTO;
    }

}
